package com.ds.sign.config;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

/**
 * 订单加签
 * @author 华为荣耀
 *
 */
@Component
public class CEB311SignSocketServer 
{
	private static Socket instance;
	
	public static void closeSocket() 
	{
		if (null != instance) 
		{
			try 
			{
				instance.close();
			} 
			catch (IOException e) 
			{
				
			}
		}
		instance = null;
	}
	
	public static Socket getSocket() 
	{
		return instance;
	}
	
	/**
	 * 启动订单加签服务-服务器端
	 */
	@PostConstruct
	public static void startSocket() 
	{
		new Thread(new Runnable() 
		{
			@Override
			public void run() 
			{
				// 1.创建Socket服务端，监听指定端口
				try 
				{
					ServerSocket serverSocket = new ServerSocket(6666);
					while (true) 
					{
						instance = serverSocket.accept();
						System.out.println("订单加签服务Socket连接已建立");
					}
				}
				catch (IOException e) 
				{
					System.out.println("订单加签服务Socket启动失败。" + e.toString());
				}
			}
		}).start();
	}
	
	public static void main(String args[]) 
	{
		new Thread(new Runnable()
		{
			@Override
			public void run() 
			{
				while (true) 
				{
					try 
					{
						Socket socket = CEB311SignSocketServer.getSocket();
						System.out.println("socket:" + socket);
						if (null != socket) 
						{
							socket.getOutputStream().write("3N1j9xUi3EbjdcRM4fxQtmXrdPE=".getBytes("UTF-8"));
							// 3.建立好连接之后,从Socket获取输入流,并建立缓冲区进行读取
					        InputStream inputStream = socket.getInputStream();
					        byte[] bytes = new byte[1024];
					        int len;
					        StringBuilder sb = new StringBuilder();
					        while ((len = inputStream.read(bytes)) != -1) {
					        	//注意指定编码格式,发送方和接收方一定要统一,建议使用UTF-8
					            sb.append(new String(bytes, 0, len, "UTF-8"));
					            if (sb.toString().contains(";end")) {
					            	break;
					            }
					        }
					        System.out.println("get sign from client: " + sb.toString().replace(";end", ""));
					        // 4.关闭流、Socket
					        //inputStream.close();
						}
						Thread.sleep(1000);
					}
					catch (SocketException ex) 
					{
						System.out.println("Socket异常." + ex.toString());
						CEB311SignSocketServer.closeSocket();
					}
					catch (Exception e) 
					{
						System.out.println(e);
						CEB311SignSocketServer.closeSocket();
					}
				}
			}
		}).start();
		
		CEB311SignSocketServer.startSocket();
	}
}
